package com.whty.ws_fengx.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @description: 上传文件控制器
 * @author: nxq email: niuxiangqian163@163.com
 * @createDate: 2020/12/19 4:09 下午
 * @updateUser: nxq email: niuxiangqian163@163.com
 * @updateDate: 2020/12/19 4:09 下午
 * @updateRemark:
 * @version: 1.0
 **/
@Controller
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${FengX.uploadPicPath}")
    private String basePath;

    private String FILE_UPLOAD_ERR = "文件上传失败";


    @ResponseBody
    @PostMapping("/upload")
    public String upload(@RequestParam("file")MultipartFile file){
        String fileName = saveFile(file);
        return "ok";
    }

    @PostMapping("/multiUpload")
    public Object multiUpload(@RequestParam("file")MultipartFile[] files){
        log.info("文件的个数:"+files.length);
        for (MultipartFile file : files){
            saveFile(file);
        }
        return "ok";
    }

    @GetMapping("/download")
    public void upload(String name, HttpServletResponse response){
        try {
            //文件输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //输出流，通过输出流将文件写回浏览器，在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jepg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0, len);
                outputStream.flush();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }



    private String saveFile(MultipartFile file){
        if (file.isEmpty()){
            return FILE_UPLOAD_ERR;
        }
        try{
            //取得文件原名 例如hello.jpg
            String originName = file.getOriginalFilename();
            //取得图片格式后缀 .jpg
            String suffix = originName.substring(originName.lastIndexOf("."));

            String fileName = UUID.randomUUID().toString() + suffix;
            File dir = new File(basePath);
            if (!dir.exists()){
                dir.mkdirs();
            }
            file.transferTo(new File(basePath + fileName));
            return fileName;
        }catch (IOException e){
            e.printStackTrace();
            return FILE_UPLOAD_ERR;
        }
    }
}
